<template>
  <div class="app-container">
    <el-form ref="contractFormRef" v-loading="loading" :model="form" :disabled="routeParams.type === 'view'"
      :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="8" v-if="routeParams.contractType === 'purchase'">
          <el-form-item label="销售合同号" prop="saleContractId">
            <sale-contract-num-select v-model:saleContractId="form.saleContractId"
              v-model:saleContractNum="form.saleContractNum" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item v-if="routeParams.contractType === 'sale'" label="销售合同号" prop="saleContractNum">
            <el-input v-model="form.saleContractNum" placeholder="请输入销售合同号" />
          </el-form-item>
          <el-form-item v-else label="采购合同号" prop="purchaseContractNum">
            <el-input v-model="form.purchaseContractNum" placeholder="请输入采购合同号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="form.projectName" placeholder="请输入项目名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运输路段" prop="transportSection">
            <el-select v-model="form.transportSection" placeholder="请选择运输路段">
              <el-option v-for="dict in transport_section" :key="dict.value" :label="dict.label"
                :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item v-if="routeParams.contractType === 'sale'" label="客户名称" prop="customerId">
            <customer-select v-model:customerId="form.customerId" v-model:customerName="form.customerName" />
          </el-form-item>
          <el-form-item v-else label="供应商名称" prop="supplierId">
            <supplier-select v-model:supplierId="form.supplierId" v-model:supplierName="form.supplierName" />
          </el-form-item>
        </el-col>
        <el-col :span="8">

        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="签订日期" prop="signDate">
            <el-date-picker clearable v-model="form.signDate" type="date" value-format="YYYY-MM-DD"
              placeholder="请选择签订日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="签订人员" prop="signStaffId">
            <!-- <staff-select v-model:staffId="form.signStaffId" v-model:staffName="form.signStaffName" /> -->
            <staff-select v-model:staffId="form.signStaffId" v-model:staffName="form.signStaffName"
              @update:staffId="handleStaffChange" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="签订部门" prop="signDept">
            <el-tree-select v-model="form.signDept" :data="deptOptions" disabled
              :props="{ value: 'deptId', label: 'deptName', children: 'children' }" value-key="deptId"
              placeholder="根据人员带出" check-strictly clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="原币价税合计" prop="originalTotalAmount">
            <el-input-number style="width: 100%;" :precision="2" v-model="form.originalTotalAmount"
              placeholder="请输入原币价税合计" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="原币无税金额" prop="originalAmount">
            <el-input-number style="width: 100%;" :precision="2" v-model="form.originalAmount"
              placeholder="请输入原币无税金额" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="原币税额" prop="originalTaxedAmount">
            <el-input-number style="width: 100%;" :precision="2" disabled v-model="form.originalTaxedAmount"
              placeholder="根据原币价税合计自动计算" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="币种" prop="currency">
            <el-select v-model="form.currency" placeholder="请选择币种">
              <el-option v-for="dict in bas_currency" :key="dict.value" :label="dict.label"
                :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="汇率" prop="exchangeRate">
            <el-input-number style="width: 100%;" :precision="6" :disabled="isExchangeRateDisabled"
              v-model="form.exchangeRate" placeholder="请输入汇率" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="本币价税合计" prop="localTotalAmount">
            <el-input-number style="width: 100%;" :precision="2" v-model="form.localTotalAmount" disabled
              placeholder="根据汇率自动计算" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="本币无税金额" prop="localAmount">
            <el-input-number style="width: 100%;" :precision="2" v-model="form.localAmount" disabled
              placeholder="根据汇率自动计算" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="本币税额" prop="localTaxedAmount">
            <el-input-number style="width: 100%;" :precision="2" v-model="form.localTaxedAmount" disabled
              placeholder="根据汇率自动计算" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="转关税" prop="transferTaxedAmount">
            <el-input-number style="width: 100%;" :precision="2" v-model="form.transferTaxedAmount"
              placeholder="请输入转关税" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="保险费" prop="insuranceAmount">
            <el-input-number style="width: 100%;" :precision="2" v-model="form.insuranceAmount" placeholder="请输入保险费" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="押车费" prop="escortAmount">
            <el-input-number style="width: 100%;" :precision="2" v-model="form.escortAmount" placeholder="请输入押车费" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" maxlength="1000" v-model="form.remark" />
      </el-form-item>
    </el-form>
    <el-row class="buttonBox">
      <el-button type="primary" @click="handleSave" v-if="routeParams.type === 'add' || routeParams.type === 'update'"
        :disabled="saveDisable">保存</el-button>
      <el-button @click="goBack">返回</el-button>
    </el-row>
  </div>

</template>
<script setup name="contractEdit" lang="ts">
import dayjs from 'dayjs';
import { getSaleContract, addSaleContract, updateSaleContract } from '@/api/finance/saleContract';
import { getPurchaseContract, addPurchaseContract, updatePurchaseContract } from '@/api/finance/purchaseContract';
import { ContractForm } from '@/api/finance/types';
import { DeptVO } from '@/api/system/dept/types';
import { listDeptIgnorePerm } from '@/api/system/dept';
import { getStaff } from '@/api/finance/staff';
const loading = ref(false);
const saveDisable = ref(false)
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const routeParams = ref<Record<string, any>>({});
const { transport_section, bas_currency } = toRefs<any>(proxy?.useDict('transport_section', 'bas_currency'));
const deptOptions = ref([]);
const isExchangeRateDisabled = ref(false);

const initFormData: ContractForm = {
  id: undefined,
  saleContractNum: undefined,
  projectName: undefined,
  transportSection: undefined,
  customerId: undefined,
  supplierId: undefined,
  signDate: dayjs().format('YYYY-MM-DD'),
  signDept: undefined,
  signStaffId: undefined,
  originalTotalAmount: undefined,
  originalAmount: undefined,
  originalTaxedAmount: undefined,
  currency: 4,
  exchangeRate: 1,
  localTotalAmount: undefined,
  localAmount: undefined,
  localTaxedAmount: undefined,
  transferTaxedAmount: undefined,
  insuranceAmount: undefined,
  escortAmount: undefined,
  remark: undefined,
}
const data = reactive({
  form: initFormData,
  rules: {
    saleContractId: [
      { required: true, message: "销售合同号不能为空", trigger: "change" }
    ],
    saleContractNum: [
      { required: true, message: "销售合同号不能为空", trigger: "blur" }
    ],
    purchaseContractNum: [
      { required: true, message: "采购合同号不能为空", trigger: "blur" }
    ],
    projectName: [
      { required: true, message: "项目名称不能为空", trigger: "blur" }
    ],
    transportSection: [
      { required: true, message: "运输路段", trigger: "change" }
    ],
    customerId: [
      { required: true, message: "客户不能为空", trigger: "change" }
    ],
    supplierId: [
      { required: true, message: "供应商不能为空", trigger: "change" }
    ],
    signDate: [
      { required: true, message: "签订日期不能为空", trigger: "blur" }
    ],
    originalTotalAmount: [
      { required: true, message: "原币价税合计不能为空", trigger: "blur" }
    ],
    originalAmount: [
      { required: true, message: "原币无税金额不能为空", trigger: "blur" }
    ],
    originalTaxedAmount: [
      { required: true, message: "原币税额不能为空", trigger: "blur" }
    ],
    currency: [
      { required: true, message: "币种不能为空", trigger: "blur" }
    ],
    exchangeRate: [
      { required: true, message: "汇率不能为空", trigger: "change" }
    ],
    localTotalAmount: [
      { required: true, message: "本币价税合计不能为空", trigger: "blur" }
    ],
    localAmount: [
      { required: true, message: "本币无税金额不能为空", trigger: "blur" }
    ],
    localTaxedAmount: [
      { required: true, message: "本币税额不能为空", trigger: "blur" }
    ],
  }
})


const { form, rules } = toRefs(data);

watch(
  () => form.value.currency,
  (newVal) => {
    if (newVal === 4) {
      form.value.exchangeRate = 1;
      isExchangeRateDisabled.value = true;
    } else {
      form.value.exchangeRate = undefined;
      isExchangeRateDisabled.value = false;
    }
    nextTick(() => {
      proxy?.$refs["contractFormRef"]?.clearValidate?.(["exchangeRate"]);
    });
  },
  { immediate: true }
);
const handleSave = async () => {
  if (saveDisable.value) return;

  const formRef = proxy.$refs["contractFormRef"];
  if (!formRef) return;

  saveDisable.value = true;

  try {
    const valid = await formRef.validate();
    if (!valid) return;

    // 验证金额逻辑
    if (!validateAmountGroup('original') || !validateAmountGroup('local')) return;

    if (routeParams.value.type === 'add') {
      await saveContract(form.value, routeParams.value.contractType === 'sale', true);
      proxy?.$modal.msgSuccess("保存成功");
    } else if (routeParams.value.type === 'update') {
      await saveContract(form.value, routeParams.value.contractType === 'sale', false);
      proxy?.$modal.msgSuccess("修改成功");
    }

    proxy.$tab.closePage(proxy.$route);
    proxy.$router.go(-1);
  } finally {
    saveDisable.value = false;
  }
};
const saveContract = async (data: any, isSale: boolean, isAdd: boolean) => {
  if (isAdd) {
    return isSale ? addSaleContract(data) : addPurchaseContract(data);
  } else {
    return isSale ? updateSaleContract(data) : updatePurchaseContract(data);
  }
};
const handleStaffChange = async (staffId: number | string) => {
  if (!staffId) {
    form.value.signDept = null
    return
  }

  const res = await getStaff(staffId)
  form.value.signDept = res.data.deptId
}

const getTreeSelect = async () => {
  const res = await listDeptIgnorePerm();
  const data = proxy?.handleTree<DeptVO>(res.data, 'deptId');
  if (data) {
    deptOptions.value = data;
  }
};
const getInfo = async () => {
  const contractType = routeParams.value.contractType;
  let res;
  if (contractType === 'sale') {
    res = await getSaleContract(routeParams.value.id);
  } else if (contractType === 'purchase') {
    res = await getPurchaseContract(routeParams.value.id);
  }
  if (res && res.data) {
    Object.assign(form.value, res.data);
  }
};


watchEffect(() => {
  const originalAmount = Number(form.value.originalAmount) || 0;
  const originalTotalAmount = Number(form.value.originalTotalAmount) || 0;
  const exchangeRate = Number(form.value.exchangeRate) || 0;
  form.value.originalTaxedAmount = Number((originalTotalAmount - originalAmount).toFixed(2));
  // 本币无税金额 = 原币无税金额 * 汇率
  form.value.localAmount = Number((originalAmount * exchangeRate).toFixed(2));

  // 本币税额 = 原币税额 * 汇率
  form.value.localTaxedAmount = Number((form.value.originalTaxedAmount * exchangeRate).toFixed(2));

  // 本币价税合计 = 原币价税合计 * 汇率
  form.value.localTotalAmount = Number((originalTotalAmount * exchangeRate).toFixed(2));
});


const validateAmountGroup = (prefix: string): boolean => {
  const amount = Number(form.value[`${prefix}Amount`] || 0);
  const taxed = Number(form.value[`${prefix}TaxedAmount`] || 0);
  const total = Number(form.value[`${prefix}TotalAmount`] || 0);
  console.log(amount, taxed, total);

  if (amount + taxed !== total) {
    proxy.$modal.msgWarning(`${prefix === "original" ? "原币" : "本币"}无税金额 + 税额 必须等于价税合计`);
    return false;
  }
  return true;
};

const goBack = () => {
  const from = proxy.$route.query.from;
  if (from) {
    proxy.$router.push(from);
  } else {
    proxy.$router.back();
  }
}
onMounted(async () => {
  loading.value = true
  routeParams.value = proxy.$route.query
  await getTreeSelect();
  if (routeParams.value.type === 'update' || routeParams.value.type === 'view') {
    await getInfo();
  }
  loading.value = false
})
</script>
<style scoped>
.buttonBox {
  position: fixed;
  bottom: 20px;
  left: 50%;
}
</style>
